<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>员工仪表板 - OpenOKR</title>
    <meta name="page-title" content="dashboard.employee">
    <link rel="stylesheet" href="/static/css/style.css">
    <script src="/static/js/i18n.js"></script>
</head>
<body>
    <nav class="navbar">
        <a href="/" class="navbar-brand" style="display: flex; align-items: center; gap: 0.5rem;">
            <img src="/static/images/openokr.png" alt="OpenOKR" style="height: 32px; width: auto;">
            <span data-i18n="app.name">OpenOKR</span>
        </a>
        <ul class="navbar-menu">
            <li><a href="/auth/dashboard" data-i18n="nav.dashboard">仪表板</a></li>
            <li>
                <select id="language-selector" onchange="switchLanguage(this.value)" style="background: transparent; border: 1px solid rgba(255,255,255,0.3); color: white; padding: 0.3rem 0.5rem; border-radius: 4px; cursor: pointer;">
                    <option value="zh">中文</option>
                    <option value="en">English</option>
                </select>
            </li>
            <li><a href="#" onclick="logout()" data-i18n="nav.logout">登出</a></li>
        </ul>
    </nav>

    <div class="container-fluid">
        <h1 style="margin-bottom: 2rem;" id="dashboard-title" data-i18n="dashboard.employee">员工仪表板</h1>

        <div class="grid grid-3">
            <!-- 工作状态更新 -->
            <div class="card">
                <div class="card-header">📍 更新工作状态</div>
                <div class="card-body">
                    <form id="status-form">
                        <div class="form-group">
                            <label class="form-label">当前状态</label>
                            <select name="work_status" class="form-select" required>
                                <option value="on_site">在岗</option>
                                <option value="remote">远程</option>
                                <option value="leave">请假</option>
                                <option value="out">外出</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label class="form-label">位置</label>
                            <input type="text" name="location" class="form-input" placeholder="例如：办公室、家中">
                        </div>
                        <div class="form-group">
                            <label class="form-label">当前任务</label>
                            <select name="objective_id" id="task-objective-select" class="form-select">
                                <option value="">选择关联的目标</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label class="form-label">任务详情</label>
                            <input type="text" name="current_task" class="form-input" placeholder="具体在做什么">
                        </div>
                        <button type="submit" class="btn btn-primary" style="width: 100%;">更新状态</button>
                    </form>
                </div>
            </div>

            <!-- 我的状态历史 -->
            <div class="card">
                <div class="card-header">📊 最近状态</div>
                <div class="card-body">
                    <div id="status-history"></div>
                </div>
            </div>

            <!-- 统计信息 -->
            <div class="card">
                <div class="card-header">📈 我的统计</div>
                <div class="card-body">
                    <div id="my-stats"></div>
                </div>
            </div>
        </div>

        <!-- 我的OKR -->
        <div class="card">
            <div class="card-header">
                🎯 我的OKR
                <button onclick="openModal('create-objective-modal')" class="btn btn-primary" style="float: right;">创建目标</button>
            </div>
            <div class="card-body">
                <div id="objectives-container"></div>
            </div>
        </div>

        <!-- 我的项目（按目标分组） -->
        <div class="card">
            <div class="card-header">
                📁 我的项目
                <button onclick="openCreateProjectModal()" class="btn btn-primary" style="float: right;">创建项目</button>
            </div>
            <div class="card-body">
                <div id="projects-container"></div>
            </div>
        </div>
    </div>

    <!-- 创建目标模态框 -->
    <div id="create-objective-modal" class="modal">
        <div class="modal-content" style="max-width: 800px;">
            <div class="modal-header">创建个人目标</div>
            <div style="margin-bottom: 1rem;">
                <button type="button" onclick="showManagerObjectives()" class="btn btn-secondary" style="width: 100%;">
                    📋 从领导目标中选择
                </button>
            </div>
            <div id="manager-objectives-list" style="display: none; margin-bottom: 1.5rem; max-height: 200px; overflow-y: auto; border: 1px solid var(--border-color); border-radius: 6px; padding: 1rem;">
                <div style="font-weight: 600; margin-bottom: 0.5rem;">领导的部门目标：</div>
                <div id="manager-objectives-container">加载中...</div>
            </div>
            <form id="create-objective-form">
                <div class="form-group">
                    <label class="form-label">目标标题</label>
                    <input type="text" name="title" id="objective-title" class="form-input" required>
                </div>
                <div class="form-group">
                    <label class="form-label">描述</label>
                    <textarea name="description" id="objective-description" class="form-textarea"></textarea>
                </div>
                <input type="hidden" name="level" value="individual">
                <div class="form-group">
                    <label class="form-label">类型</label>
                    <select name="type" id="objective-type" class="form-select" required>
                        <option value="operational">经营目标</option>
                        <option value="strategic">战略目标</option>
                        <option value="development">研发目标</option>
                    </select>
                </div>
                <div class="grid grid-2">
                    <div class="form-group">
                        <label class="form-label">开始日期</label>
                        <input type="date" name="start_date" id="objective-start-date" class="form-input" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">结束日期</label>
                        <input type="date" name="end_date" id="objective-end-date" class="form-input" required>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" onclick="closeModal('create-objective-modal')" class="btn btn-secondary">取消</button>
                    <button type="submit" class="btn btn-primary">创建</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 创建项目模态框 -->
    <div id="create-project-modal" class="modal">
        <div class="modal-content">
            <div class="modal-header">创建项目（服务于目标的具体规划）</div>
            <form id="create-project-form">
                <div class="form-group">
                    <label class="form-label">关联目标 *</label>
                    <select name="objective_id" id="project-objective-select" class="form-select" required>
                        <option value="">选择此项目服务的目标</option>
                    </select>
                    <small style="color: var(--text-secondary); font-size: 0.875rem;">项目是实现目标的具体行动计划</small>
                </div>
                <div class="form-group">
                    <label class="form-label">项目名称</label>
                    <input type="text" name="name" class="form-input" required placeholder="例如：XX系统开发、客户拓展计划">
                </div>
                <div class="form-group">
                    <label class="form-label">项目描述</label>
                    <textarea name="description" class="form-textarea" placeholder="详细说明项目如何帮助实现目标"></textarea>
                </div>
                <div class="grid grid-2">
                    <div class="form-group">
                        <label class="form-label">开始日期</label>
                        <input type="date" name="start_date" class="form-input" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">结束日期</label>
                        <input type="date" name="end_date" class="form-input">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" onclick="closeModal('create-project-modal')" class="btn btn-secondary">取消</button>
                    <button type="submit" class="btn btn-primary">创建</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 更新关键成果模态框 -->
    <div id="update-kr-modal" class="modal">
        <div class="modal-content">
            <div class="modal-header">更新关键成果</div>
            <form id="update-kr-form">
                <input type="hidden" id="kr-id" name="kr_id">
                <div class="form-group">
                    <label class="form-label" id="kr-title">关键成果</label>
                    <input type="number" step="0.01" name="current_value" class="form-input" required>
                </div>
                <div class="form-group">
                    <label class="form-label">备注</label>
                    <textarea name="notes" class="form-textarea" placeholder="说明本次更新"></textarea>
                </div>
                <div class="modal-footer">
                    <button type="button" onclick="closeModal('update-kr-modal')" class="btn btn-secondary">取消</button>
                    <button type="submit" class="btn btn-primary">更新</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 编辑项目模态框 -->
    <div id="edit-project-modal" class="modal">
        <div class="modal-content">
            <div class="modal-header">编辑项目</div>
            <form id="edit-project-form">
                <input type="hidden" id="edit-project-id" name="project_id">
                <input type="hidden" id="edit-project-old-objective-id" name="old_objective_id">
                <div class="form-group">
                    <label class="form-label">关联目标 *</label>
                    <select name="objective_id" id="edit-project-objective-select" class="form-select" required>
                        <option value="">选择此项目服务的目标</option>
                    </select>
                    <small style="color: var(--text-secondary); font-size: 0.875rem;">可以重新选择项目关联的目标</small>
                </div>
                <div class="form-group">
                    <label class="form-label">项目名称</label>
                    <input type="text" id="edit-project-name" name="name" class="form-input" required>
                </div>
                <div class="form-group">
                    <label class="form-label">项目描述</label>
                    <textarea id="edit-project-description" name="description" class="form-textarea"></textarea>
                </div>
                <div class="form-group">
                    <label class="form-label">进度 (%)</label>
                    <input type="number" id="edit-project-progress" name="progress" class="form-input" min="0" max="100" required>
                </div>
                <div class="form-group">
                    <label class="form-label">状态</label>
                    <select id="edit-project-status" name="status" class="form-select" required>
                        <option value="active">进行中</option>
                        <option value="completed">已完成</option>
                        <option value="on_hold">暂停</option>
                        <option value="cancelled">已取消</option>
                    </select>
                </div>
                <div class="grid grid-2">
                    <div class="form-group">
                        <label class="form-label">开始日期</label>
                        <input type="date" id="edit-project-start" name="start_date" class="form-input" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">结束日期</label>
                        <input type="date" id="edit-project-end" name="end_date" class="form-input">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" onclick="confirmDeleteProject()" class="btn btn-danger" style="margin-right: auto;">删除项目</button>
                    <button type="button" onclick="closeModal('edit-project-modal')" class="btn btn-secondary">取消</button>
                    <button type="submit" class="btn btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>

    <script src="/static/js/common.js"></script>
    <script>
        let currentUser = null;

        // 获取当前用户信息
        async function loadCurrentUser() {
            try {
                const response = await fetch('/auth/me');
                if (!response.ok) throw new Error('Failed to fetch user info');
                currentUser = await response.json();

                // 更新页面标题
                document.getElementById('dashboard-title').textContent = `${currentUser.full_name}的仪表板`;
                document.title = `${currentUser.full_name}的仪表板 - OpenOKR`;

                // 加载目标到下拉框
                loadObjectivesForSelect();
            } catch (error) {
                console.error('获取用户信息失败:', error);
            }
        }

        // 加载目标到任务选择下拉框
        async function loadObjectivesForSelect() {
            try {
                const objectives = await getObjectives();
                const select = document.getElementById('task-objective-select');

                objectives.forEach(obj => {
                    const option = document.createElement('option');
                    option.value = obj.id;
                    option.textContent = obj.title;
                    select.appendChild(option);
                });
            } catch (error) {
                console.error('加载目标选项失败:', error);
            }
        }

        // 更新工作状态
        document.getElementById('status-form').addEventListener('submit', async (e) => {
            e.preventDefault();
            const formData = new FormData(e.target);
            const data = Object.fromEntries(formData);

            try {
                await updateStatus(data);
                showNotification('状态更新成功', 'success');
                loadStatusHistory();
            } catch (error) {
                showNotification('更新失败: ' + error.message, 'error');
            }
        });

        // 加载状态历史
        async function loadStatusHistory() {
            try {
                const data = await apiRequest('/api/status/me?limit=5');
                const container = document.getElementById('status-history');

                if (data.length === 0) {
                    container.innerHTML = '<p style="color: var(--text-secondary);">暂无历史记录</p>';
                    return;
                }

                container.innerHTML = data.map(status => `
                    <div style="padding: 0.75rem 0; border-bottom: 1px solid var(--border-color);">
                        <div style="display: flex; justify-content: space-between; margin-bottom: 0.25rem;">
                            ${getStatusBadge(status.work_status)}
                            <span style="font-size: 0.875rem; color: var(--text-secondary);">${formatDate(status.created_at)}</span>
                        </div>
                        ${status.current_task ? `<div style="font-size: 0.875rem; color: var(--text-secondary);">${status.current_task}</div>` : ''}
                    </div>
                `).join('');
            } catch (error) {
                console.error('加载状态历史失败:', error);
            }
        }

        // 加载统计信息
        async function loadStats() {
            try {
                const objectives = await getObjectives();
                const projects = await getProjects();

                const container = document.getElementById('my-stats');
                const activeObjectives = objectives.filter(o => o.status === 'active').length;
                const activeProjects = projects.filter(p => p.status === 'active').length;
                const avgProgress = objectives.length > 0
                    ? Math.round(objectives.reduce((sum, o) => sum + o.progress, 0) / objectives.length)
                    : 0;

                container.innerHTML = `
                    <div style="text-align: center; margin-bottom: 1rem;">
                        <div style="font-size: 2rem; font-weight: 700; color: var(--primary-color);">${activeObjectives}</div>
                        <div style="color: var(--text-secondary);">活跃目标</div>
                    </div>
                    <div style="text-align: center; margin-bottom: 1rem;">
                        <div style="font-size: 2rem; font-weight: 700; color: var(--success-color);">${activeProjects}</div>
                        <div style="color: var(--text-secondary);">活跃项目</div>
                    </div>
                    <div style="text-align: center;">
                        <div style="font-size: 2rem; font-weight: 700; color: var(--warning-color);">${avgProgress}%</div>
                        <div style="color: var(--text-secondary);">平均进度</div>
                    </div>
                `;
            } catch (error) {
                console.error('加载统计失败:', error);
            }
        }

        // 加载目标
        async function loadObjectives() {
            try {
                const objectives = await getObjectives();
                const container = document.getElementById('objectives-container');

                if (objectives.length === 0) {
                    container.innerHTML = '<p style="text-align: center; color: var(--text-secondary);">暂无目标，点击右上角创建</p>';
                    return;
                }

                container.innerHTML = objectives.map(obj => `
                    <div class="card" style="margin-bottom: 1rem;">
                        <h3 style="margin-bottom: 0.5rem;">${obj.title}</h3>
                        <p style="color: var(--text-secondary); margin-bottom: 1rem;">${obj.description || ''}</p>
                        <div style="margin-bottom: 1rem;">
                            <div class="progress">
                                <div class="progress-bar ${obj.progress >= 70 ? 'success' : obj.progress >= 40 ? 'warning' : 'danger'}"
                                     style="width: ${obj.progress}%"></div>
                            </div>
                            <span style="font-size: 0.875rem; color: var(--text-secondary);">${obj.progress}%</span>
                        </div>
                        <div style="margin-bottom: 1rem;">
                            <strong>关键成果:</strong>
                            ${obj.key_results.map(kr => `
                                <div style="display: flex; justify-content: space-between; align-items: center; padding: 0.5rem; background: var(--background-color); border-radius: 4px; margin-top: 0.5rem;">
                                    <span>${kr.title}</span>
                                    <div>
                                        <span style="margin-right: 1rem;">${kr.current_value}/${kr.target_value} ${kr.unit || ''}</span>
                                        <button class="btn btn-primary" style="font-size: 0.75rem; padding: 0.25rem 0.5rem;"
                                                onclick="openUpdateKRModal(${kr.id}, '${kr.title}')">更新</button>
                                    </div>
                                </div>
                            `).join('')}
                        </div>
                        <div style="display: flex; justify-content: space-between; align-items: center;">
                            <div>
                                ${getStatusBadge(obj.status)}
                                <span style="margin-left: 0.5rem; font-size: 0.875rem; color: var(--text-secondary);">
                                    ${formatDate(obj.start_date)} - ${formatDate(obj.end_date)}
                                </span>
                            </div>
                        </div>
                    </div>
                `).join('');
            } catch (error) {
                showNotification('加载目标失败', 'error');
            }
        }

        // 加载项目（按目标分组）
        async function loadProjects() {
            try {
                const [projects, objectives] = await Promise.all([
                    getProjects({ include_objectives: true }),
                    getObjectives()
                ]);
                const container = document.getElementById('projects-container');

                if (projects.length === 0) {
                    container.innerHTML = '<p style="text-align: center; color: var(--text-secondary);">暂无项目，点击右上角创建项目来支持你的目标</p>';
                    return;
                }

                // 按目标分组项目
                const projectsByObjective = {};
                const unlinkedProjects = [];

                projects.forEach(proj => {
                    if (proj.linked_objectives && proj.linked_objectives.length > 0) {
                        proj.linked_objectives.forEach(link => {
                            const objId = link.objective_id;
                            if (!projectsByObjective[objId]) {
                                projectsByObjective[objId] = {
                                    objective: link.objective,
                                    projects: []
                                };
                            }
                            projectsByObjective[objId].projects.push(proj);
                        });
                    } else {
                        unlinkedProjects.push(proj);
                    }
                });

                let html = '';

                // 显示按目标分组的项目
                Object.values(projectsByObjective).forEach(group => {
                    const obj = group.objective;
                    html += `
                        <div style="margin-bottom: 2rem;">
                            <div style="display: flex; align-items: center; margin-bottom: 1rem; padding-bottom: 0.5rem; border-bottom: 2px solid var(--primary-color);">
                                <span style="font-size: 1.125rem; font-weight: 600; color: var(--primary-color);">
                                    🎯 ${obj.title}
                                </span>
                                <span style="margin-left: 1rem; font-size: 0.875rem; color: var(--text-secondary);">
                                    ${group.projects.length} 个项目
                                </span>
                            </div>
                            ${group.projects.map(proj => renderProjectCard(proj)).join('')}
                        </div>
                    `;
                });

                // 显示未关联的项目
                if (unlinkedProjects.length > 0) {
                    html += `
                        <div style="margin-bottom: 2rem;">
                            <div style="display: flex; align-items: center; margin-bottom: 1rem; padding-bottom: 0.5rem; border-bottom: 2px solid var(--secondary-color);">
                                <span style="font-size: 1.125rem; font-weight: 600; color: var(--secondary-color);">
                                    📋 未关联目标的项目
                                </span>
                            </div>
                            ${unlinkedProjects.map(proj => renderProjectCard(proj)).join('')}
                        </div>
                    `;
                }

                container.innerHTML = html;
            } catch (error) {
                console.error('加载项目失败:', error);
                showNotification('加载项目失败', 'error');
            }
        }

        // 渲染项目卡片
        function renderProjectCard(proj) {
            return `
                <div class="card" style="margin-bottom: 1rem; margin-left: 1.5rem;">
                    <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 0.5rem;">
                        <h3 style="margin: 0; font-size: 1rem;">${proj.name}</h3>
                        <button class="btn btn-secondary" style="font-size: 0.75rem; padding: 0.25rem 0.5rem;"
                                onclick="openEditProjectModal(${proj.id})">编辑</button>
                    </div>
                    <p style="color: var(--text-secondary); margin-bottom: 1rem; font-size: 0.875rem;">${proj.description || ''}</p>
                    <div style="margin-bottom: 0.75rem;">
                        <div class="progress" style="height: 8px;">
                            <div class="progress-bar ${proj.progress >= 70 ? 'success' : proj.progress >= 40 ? 'warning' : 'danger'}"
                                 style="width: ${proj.progress}%"></div>
                        </div>
                        <span style="font-size: 0.875rem; color: var(--text-secondary);">${proj.progress}%</span>
                    </div>
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <div>
                            ${getStatusBadge(proj.status)}
                        </div>
                        <span style="font-size: 0.75rem; color: var(--text-secondary);">
                            📅 ${formatDate(proj.start_date)} ${proj.end_date ? '- ' + formatDate(proj.end_date) : ''}
                        </span>
                    </div>
                </div>
            `;
        }

        // 打开编辑项目模态框
        async function openEditProjectModal(projectId) {
            try {
                const [project, objectives] = await Promise.all([
                    fetch(`/api/projects/${projectId}`).then(r => r.json()),
                    getObjectives()
                ]);

                // 填充基本信息
                document.getElementById('edit-project-id').value = project.id;
                document.getElementById('edit-project-name').value = project.name;
                document.getElementById('edit-project-description').value = project.description || '';
                document.getElementById('edit-project-progress').value = project.progress || 0;
                document.getElementById('edit-project-status').value = project.status;
                document.getElementById('edit-project-start').value = project.start_date;
                document.getElementById('edit-project-end').value = project.end_date || '';

                // 填充目标下拉框
                const select = document.getElementById('edit-project-objective-select');
                select.innerHTML = '<option value="">选择此项目服务的目标</option>';

                objectives.forEach(obj => {
                    const option = document.createElement('option');
                    option.value = obj.id;
                    option.textContent = obj.title;
                    select.appendChild(option);
                });

                // 设置当前关联的目标
                if (project.linked_objectives && project.linked_objectives.length > 0) {
                    const currentObjectiveId = project.linked_objectives[0].objective_id;
                    select.value = currentObjectiveId;
                    document.getElementById('edit-project-old-objective-id').value = currentObjectiveId;
                } else {
                    document.getElementById('edit-project-old-objective-id').value = '';
                }

                openModal('edit-project-modal');
            } catch (error) {
                showNotification('加载项目失败: ' + error.message, 'error');
            }
        }

        // 确认删除项目
        function confirmDeleteProject() {
            if (confirm('确定要删除这个项目吗？此操作无法撤销。')) {
                deleteProject();
            }
        }

        // 删除项目
        async function deleteProject() {
            const projectId = document.getElementById('edit-project-id').value;

            try {
                await apiRequest(`/api/projects/${projectId}`, {
                    method: 'DELETE'
                });

                showNotification('项目已删除', 'success');
                closeModal('edit-project-modal');
                loadProjects();
                loadStats();
            } catch (error) {
                showNotification('删除失败: ' + error.message, 'error');
            }
        }

        // 显示领导目标列表
        async function showManagerObjectives() {
            const listDiv = document.getElementById('manager-objectives-list');
            const container = document.getElementById('manager-objectives-container');

            if (listDiv.style.display === 'none') {
                listDiv.style.display = 'block';

                try {
                    // 获取领导的目标（通过manager_id）
                    const response = await fetch(`/api/objectives?owner_id=${currentUser.manager_id}`);
                    if (!response.ok) throw new Error('Failed to fetch manager objectives');
                    const objectives = await response.json();

                    if (objectives.length === 0) {
                        container.innerHTML = '<p style="color: var(--text-secondary);">领导暂无部门目标</p>';
                        return;
                    }

                    container.innerHTML = objectives.map(obj => `
                        <div style="padding: 0.75rem; background: var(--background-color); border-radius: 4px; margin-bottom: 0.5rem; cursor: pointer;"
                             onclick="selectManagerObjective(${JSON.stringify(obj).replace(/"/g, '&quot;')})">
                            <div style="font-weight: 500;">${obj.title}</div>
                            <div style="font-size: 0.875rem; color: var(--text-secondary); margin-top: 0.25rem;">
                                ${obj.description || ''}
                            </div>
                            <div style="margin-top: 0.5rem;">
                                <span class="badge badge-primary">${obj.type === 'operational' ? '经营' : obj.type === 'strategic' ? '战略' : '研发'}</span>
                                <span style="margin-left: 0.5rem; font-size: 0.75rem; color: var(--text-secondary);">
                                    进度: ${obj.progress}%
                                </span>
                            </div>
                        </div>
                    `).join('');
                } catch (error) {
                    container.innerHTML = '<p style="color: var(--danger-color);">加载失败</p>';
                    console.error('加载领导目标失败:', error);
                }
            } else {
                listDiv.style.display = 'none';
            }
        }

        // 选择领导目标并填充表单
        function selectManagerObjective(obj) {
            document.getElementById('objective-title').value = obj.title;
            document.getElementById('objective-description').value = obj.description || '';
            document.getElementById('objective-type').value = obj.type;
            document.getElementById('objective-start-date').value = obj.start_date;
            document.getElementById('objective-end-date').value = obj.end_date;

            // 隐藏领导目标列表
            document.getElementById('manager-objectives-list').style.display = 'none';

            showNotification('已导入领导目标，请根据需要修改', 'success');
        }

        // 打开更新关键成果模态框
        function openUpdateKRModal(krId, krTitle) {
            document.getElementById('kr-id').value = krId;
            document.getElementById('kr-title').textContent = krTitle;
            openModal('update-kr-modal');
        }

        // 创建目标
        document.getElementById('create-objective-form').addEventListener('submit', async (e) => {
            e.preventDefault();
            const formData = new FormData(e.target);
            const data = Object.fromEntries(formData);

            try {
                await createObjective(data);
                showNotification('目标创建成功', 'success');
                closeModal('create-objective-modal');
                e.target.reset();
                loadObjectives();
                loadStats();
            } catch (error) {
                showNotification('创建失败: ' + error.message, 'error');
            }
        });

        // 打开创建项目模态框
        async function openCreateProjectModal() {
            // 加载目标到下拉框
            try {
                const objectives = await getObjectives();
                const select = document.getElementById('project-objective-select');

                // 清空并重新填充
                select.innerHTML = '<option value="">选择此项目服务的目标</option>';

                if (objectives.length === 0) {
                    showNotification('请先创建目标，项目需要关联到具体目标', 'warning');
                    return;
                }

                objectives.forEach(obj => {
                    const option = document.createElement('option');
                    option.value = obj.id;
                    option.textContent = obj.title;
                    select.appendChild(option);
                });

                openModal('create-project-modal');
            } catch (error) {
                showNotification('加载目标失败', 'error');
            }
        }

        // 创建项目并关联到目标
        document.getElementById('create-project-form').addEventListener('submit', async (e) => {
            e.preventDefault();
            const formData = new FormData(e.target);
            const data = Object.fromEntries(formData);

            try {
                // 创建项目
                const project = await createProject({
                    name: data.name,
                    description: data.description,
                    start_date: data.start_date,
                    end_date: data.end_date
                });

                // 关联到目标
                if (data.objective_id) {
                    await apiRequest('/api/projects/link', {
                        method: 'POST',
                        body: JSON.stringify({
                            project_id: project.id,
                            objective_id: parseInt(data.objective_id)
                        })
                    });
                }

                showNotification('项目创建成功并已关联到目标', 'success');
                closeModal('create-project-modal');
                e.target.reset();
                loadProjects();
                loadStats();
            } catch (error) {
                showNotification('创建失败: ' + error.message, 'error');
            }
        });

        // 更新关键成果
        document.getElementById('update-kr-form').addEventListener('submit', async (e) => {
            e.preventDefault();
            const formData = new FormData(e.target);
            const data = Object.fromEntries(formData);
            const krId = data.kr_id;

            try {
                await apiRequest(`/api/objectives/key_results/${krId}`, {
                    method: 'PUT',
                    body: JSON.stringify({
                        current_value: parseFloat(data.current_value),
                        notes: data.notes
                    })
                });
                showNotification('更新成功', 'success');
                closeModal('update-kr-modal');
                e.target.reset();
                loadObjectives();
                loadStats();
            } catch (error) {
                showNotification('更新失败: ' + error.message, 'error');
            }
        });

        // 编辑项目
        document.getElementById('edit-project-form').addEventListener('submit', async (e) => {
            e.preventDefault();
            const formData = new FormData(e.target);
            const data = Object.fromEntries(formData);
            const projectId = data.project_id;
            const newObjectiveId = parseInt(data.objective_id);
            const oldObjectiveId = data.old_objective_id ? parseInt(data.old_objective_id) : null;

            try {
                // 1. 更新项目基本信息
                await apiRequest(`/api/projects/${projectId}`, {
                    method: 'PUT',
                    body: JSON.stringify({
                        name: data.name,
                        description: data.description,
                        progress: parseInt(data.progress),
                        status: data.status,
                        start_date: data.start_date,
                        end_date: data.end_date
                    })
                });

                // 2. 如果目标发生变化，更新关联关系
                if (newObjectiveId && newObjectiveId !== oldObjectiveId) {
                    // 删除旧关联（如果存在）
                    if (oldObjectiveId) {
                        try {
                            // 获取旧的link_id
                            const project = await fetch(`/api/projects/${projectId}`).then(r => r.json());
                            const oldLink = project.linked_objectives?.find(l => l.objective_id === oldObjectiveId);
                            if (oldLink) {
                                await apiRequest(`/api/projects/link/${oldLink.id}`, {
                                    method: 'DELETE'
                                });
                            }
                        } catch (err) {
                            console.log('删除旧关联失败:', err);
                        }
                    }

                    // 创建新关联
                    await apiRequest('/api/projects/link', {
                        method: 'POST',
                        body: JSON.stringify({
                            project_id: parseInt(projectId),
                            objective_id: newObjectiveId
                        })
                    });
                }

                showNotification('项目更新成功', 'success');
                closeModal('edit-project-modal');
                e.target.reset();
                loadProjects();
                loadStats();
            } catch (error) {
                showNotification('更新失败: ' + error.message, 'error');
            }
        });

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', () => {
            loadCurrentUser();
            loadStatusHistory();
            loadStats();
            loadObjectives();
            loadProjects();
        });
    </script>
</body>
</html>